package com.zhubayi.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhubayi.entity.Category;
import com.zhubayi.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 祝八一
 */
@Controller
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @GetMapping("toadd")
    public String toAdd(){
        return "admin/addCategory";
    }
    @PostMapping("add")
    public String add(@RequestParam String name){
        System.out.println(name);
        categoryService.add(name);
        return "admin/addCategory";
    }
    @GetMapping("tolist")
    public String tolist(Model model){
        //只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
       // PageHelper.startPage(1, 3).setOrderBy("id desc");
        List<Category> list=categoryService.queryAll();
        PageInfo<Category> userPageInfo = new PageInfo<>(list);
        model.addAttribute("categoryList",list);
        return "admin/category_list";
    }
    @GetMapping("toupdate/{id}")
    public String toupdate(@PathVariable("id") Integer id,Model model){
       Category category= categoryService.queryById(id);
        model.addAttribute("category",category);
        return "admin/addCategory";
    }
    @PostMapping("updateOrAdd")
    public String update(@RequestParam String id,@RequestParam String name,Model model){
        if ("".equals(id)){
            //增加
            categoryService.add(name);
        }else {
            //修改
            categoryService.update(Integer.parseInt(id),name);
        }
        List<Category> list=categoryService.queryAll();
        model.addAttribute("categoryList",list);
        return "redirect:/category/tolist";
    }
    @ResponseBody
    @RequestMapping("del/{id}")
    public boolean del(@PathVariable("id") Integer id){
        categoryService.del(id);
        return true;
    }
    @PostMapping("/search")
    public String search(@RequestParam String name,Model model){
        System.out.println(name);
        if ("".equals(name)){
            return "redirect:/category/tolist";
        }
          List<Category> categorys=  categoryService.queryByName(name);
            model.addAttribute("categoryList",categorys);

        model.addAttribute("name",name);
        return "admin/category_list";

    }
}
